package com.eventur;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView.ScaleType;

public class ListViewActivity extends Activity implements LocationListener{

	private static String tag = "ListViewActivity";

	private LocationManager locationManager;
	private Location location = null;
	private double currentLatitude=0.0;
	private double currentLongitude=0.0;

	private static final int MENU_HOME = Menu.FIRST;
	//private static final int MENU_QUIT = Menu.FIRST+1;

	public ArrayList<Event> eventsList = null;
	public ArrayList<Event> todayEventsList = null;
	public ArrayList<Event> tomorrowEventsList = null;
	public ArrayList<Event> weekEventsList = null;

	private static String category =null;
	private static String attribute = null;
	private static String searchValue = null;

	ListEvents listEvents = new ListEvents();


	private HashMap<String, ArrayList<Event>> collection = null;


	@Override
	public void onStart(){
		super.onStart();
		//eventsList.clear();
	}
	@Override
	public void onDestroy(){
		super.onDestroy();
		eventsList.clear();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	@Override
	protected void onResume(){
		super.onResume();
	}

	@Override
	protected void onPause(){
		super.onPause();
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0,MENU_HOME,0,"Home");
		//menu.add(0,MENU_QUIT,1,"Quit");
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item){
		switch(item.getItemId()	){
		case MENU_HOME: Intent intent = new Intent(this, MainActivity.class);;
		startActivity(intent);this.finish();
		return true;
		//case MENU_QUIT: int pid = android.os.Process.myPid();
		//android.os.Process.killProcess(pid); finish();
		//return true;
		}
		return false;

	}


	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);



		eventsList = new ArrayList<Event>();
		Bundle bundle = getIntent().getExtras();

		if (bundle != null) {
			
			eventsList.clear();
			category= bundle.getString("category");

			if(category.equalsIgnoreCase("My Location") || category.equalsIgnoreCase("Map")){
				final Bundle b = new Bundle();

				locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
				locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
				location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
				try{
					System.out.println("Fetching Location:");
					currentLatitude=location.getLatitude();
					currentLongitude=location.getLongitude();
					System.out.println("latitude/long obtained:"+currentLatitude+":"+currentLongitude);
				}catch(Exception e){
					while(location.getLatitude()==0 || location.getLongitude()==0){
						locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
					}
					//interchanging values here
					currentLongitude=location.getLatitude();
					currentLatitude=location.getLongitude();
				}
				b.putDouble("currentLatitude",currentLatitude);
				b.putDouble("currentLongitude",currentLongitude);
				
				if(category.equalsIgnoreCase("Map")){
					Intent intent = new Intent(ListViewActivity.this, MapViewActivity.class);
					b.putString("key", "all");
					intent.putExtras(b);
					startActivity(intent);
					this.finish();


				}
				else{
					eventsList.clear();
					System.out.println("placing the current lat lon in bundle:"+currentLatitude+currentLongitude);
					setContentView(R.layout.simplelistview);
					final ListView l1 = (ListView) findViewById(R.id.ListView02);
					
					eventsList = listEvents.getListByLocation(currentLatitude,currentLongitude);
					if(eventsList.size()!=0){
						final String [] eventTitleArray = new String[eventsList.size()];
						String [] eventDateArray = new String[eventsList.size()];
						String [] eventImageLinkArray = new String[eventsList.size()];
						Event event = new Event();
						for(int i=0;i<eventsList.size();i++){
							event = eventsList.get(i);
							eventTitleArray[i] = event.getTitle();
							if(event.getDistance()!=0.0)
								eventDateArray[i] = event.getsDate() +" \n " +Double.toString(event.getDistance())+" miles";
							else
								eventDateArray[i] = event.getsDate();					
							eventImageLinkArray[i] = event.getImageLink();
							Log.i(tag , "event detail"+event.getTitle());
						}
						l1.setAdapter(new EfficientAdapter(this,eventTitleArray,eventDateArray,eventImageLinkArray));
						l1.setFocusable(false);
						l1.setOnItemClickListener(new OnItemClickListener() {
							@Override
							public void onItemClick(AdapterView<?> arg0, View arg1,
									int position, long arg3) {
								Intent intent = new Intent(ListViewActivity.this, DisplayActivity.class);
					
								System.out.println("position in list:"+position);
								System.out.println("title name in the list:"+eventTitleArray[position]);
								System.out.println("placing the current lat lon in bundle:"+currentLatitude+currentLongitude);
								b.putString("eventTitle", eventTitleArray[position]);
								b.putString("key", "single");
								
								
								intent.putExtras(b);
								startActivity(intent);

								Toast.makeText(getApplicationContext(), "Detailed view for the Event", Toast.LENGTH_SHORT).show();
							}
						});
					}
					else{
						/*final String [] eventTitleArray = {"No Events to Display"};
						String [] eventDateArray = new String[1];
						eventDateArray[0]= "";
						String [] eventImageLinkArray = new String[1];
						l1.setAdapter(new EfficientAdapter(this,eventTitleArray,eventDateArray,eventImageLinkArray));*/
						final AlertDialog.Builder wrongAddressAlert = new AlertDialog.Builder(ListViewActivity.this);
						wrongAddressAlert.setTitle("No Events Found");
						wrongAddressAlert.setMessage("Please select a different category and search again");
						wrongAddressAlert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int whichButton) {
								finish();
								return;
							}
						});
						wrongAddressAlert.show();

					}
				}
			}else if(category.equals("Date")){
				setContentView(R.layout.simplelistview);
				final ListView l1 = (ListView) findViewById(R.id.ListView02);

				attribute = bundle.getString("attribute");
				eventsList.clear();
				eventsList = listEvents.getListByTime(attribute);
				if(eventsList.size()!=0){
					final String [] eventTitleArray = new String[eventsList.size()];
					String [] eventDateArray = new String[eventsList.size()];
					String [] eventImageLinkArray = new String[eventsList.size()];
					Event event = new Event();
					for(int i=0;i<eventsList.size();i++){
						event = eventsList.get(i);
						eventTitleArray[i] = event.getTitle();
						if(event.getDistance()!=0.0)
							eventDateArray[i] = event.getsDate() +" \n " +Double.toString(event.getDistance())+" miles";
						else
							eventDateArray[i] = event.getsDate();					
						eventImageLinkArray[i] = event.getImageLink();
						Log.i(tag , "event detail"+event.getTitle());
					}
					l1.setAdapter(new EfficientAdapter(this,eventTitleArray,eventDateArray,eventImageLinkArray));
					l1.setFocusable(false);
					l1.setOnItemClickListener(new OnItemClickListener() {
						@Override
						public void onItemClick(AdapterView<?> arg0, View arg1,
								int position, long arg3) {
							Intent intent = new Intent(ListViewActivity.this, DisplayActivity.class);
							Bundle b = new Bundle();
							System.out.println("position in list:"+position);
							System.out.println("title name in the list:"+eventTitleArray[position]);
							b.putString("eventTitle", eventTitleArray[position]);
							intent.putExtras(b);
							startActivity(intent);

							Toast.makeText(getApplicationContext(), "Detailed view for the Event", Toast.LENGTH_SHORT).show();


						}
					});
				}else{
					/*final String [] eventTitleArray = {"No Events to Display for the below Selected Time"};
					String [] eventDateArray = new String[1];
					eventDateArray[0]= attribute;
					String [] eventImageLinkArray = new String[1];
					l1.setAdapter(new EfficientAdapter(this,eventTitleArray,eventDateArray,eventImageLinkArray));
*/
					final AlertDialog.Builder wrongAddressAlert = new AlertDialog.Builder(ListViewActivity.this);
					wrongAddressAlert.setTitle("No Events Found");
					wrongAddressAlert.setMessage("Please select a different Date and search again");
					wrongAddressAlert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							finish();
							return;
						}
					});
					wrongAddressAlert.show();
				}
			}
			else{
				setContentView(R.layout.homescreen);
				final ListView l1 = (ListView) findViewById(R.id.ListView01);
				eventsList.clear();
				attribute = bundle.getString("attribute");
				if(category.equals("search")){
					searchValue = bundle.getString("searchValue");
					eventsList = listEvents.getListBySearch(attribute,searchValue);
				}
				else{
					eventsList = listEvents.getList(category,attribute);
				}
				System.out.println("Events list size after searching:"+eventsList.size());
				if(eventsList.size()!=0){
					collection  = listEvents.getLists(eventsList);

					todayEventsList = (ArrayList<Event>) collection.get("today");
					tomorrowEventsList = (ArrayList<Event>) collection.get("tomorrow");
					weekEventsList = (ArrayList<Event>) collection.get("week");
					System.out.println("In collection building:today:"+todayEventsList.size()+"tomo:"+tomorrowEventsList.size()+"week:"+weekEventsList.size());

					Toast.makeText(getApplicationContext(), eventsList.size()+" events found in this category", Toast.LENGTH_SHORT).show();

					try{
						System.out.println("Number of today events:"+todayEventsList.size());
						System.out.println("Number of tomorrow events:"+tomorrowEventsList.size());
						System.out.println("Number of week events:"+weekEventsList.size());

						Event event = new Event();
						final String [] eventTitleArray = new String[eventsList.size()];
						String [] eventDateArray = new String[eventsList.size()];
						String [] eventImageLinkArray = new String[eventsList.size()];

						System.out.println("Processing today list");
						for(int i=0;i<eventsList.size();i++){
							event = eventsList.get(i);
							eventTitleArray[i] = event.getTitle();
							if(event.getDistance()!=0.0)
								eventDateArray[i] = event.getsDate() +" \n " +Double.toString(event.getDistance())+" miles";
							else
								eventDateArray[i] = event.getsDate();					
							eventImageLinkArray[i] = event.getImageLink();

							Log.i(tag , "event detail"+event.getTitle());
						}

						l1.setAdapter(new EfficientAdapter(ListViewActivity.this,eventTitleArray,eventDateArray,eventImageLinkArray));
						l1.setFocusable(false);
						l1.setOnItemClickListener(new OnItemClickListener() {
							@Override
							public void onItemClick(AdapterView<?> arg0, View arg1,
									int position, long arg3) {
								Intent intent = new Intent(ListViewActivity.this, DisplayActivity.class);
								Bundle b = new Bundle();
								System.out.println("position in list:"+position);
								System.out.println("title name in the list:"+eventTitleArray[position]);
								b.putString("eventTitle", eventTitleArray[position]);
								intent.putExtras(b);
								startActivity(intent);

								Toast.makeText(getApplicationContext(), "Detailed view for the Event", Toast.LENGTH_SHORT).show();
							}
						});
					}
					catch(Exception e){
						e.printStackTrace();
					}
				}else{
				/*	final String [] eventTitleArray = new String [1];
					eventTitleArray[0]= "No Events to Display for \n"+category+" -> "+attribute;
					String [] eventDateArray = new String[1];
					eventDateArray[0]= "Select some other category to change the search text";
					String [] eventImageLinkArray = new String[1];
					l1.setAdapter(new EfficientAdapter(this,eventTitleArray,eventDateArray,eventImageLinkArray));
				*/
					final AlertDialog.Builder wrongAddressAlert = new AlertDialog.Builder(ListViewActivity.this);
					wrongAddressAlert.setTitle("No Events Found");
					wrongAddressAlert.setMessage("Please select a different category or check the spelling and search again");
					wrongAddressAlert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							finish();
							return;
						}
					});
					wrongAddressAlert.show();

				}

				Button todayButton = (Button) findViewById(R.id.todayButton);
				todayButton.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
						final String [] eventTitleArray;
						String [] eventDateArray;
						String [] eventImageLinkArray;

						Event event = new Event();
						System.out.println("today button clicked");
						
						if(todayEventsList.size()!=0 || eventsList.size()!=0){

							eventTitleArray = new String[todayEventsList.size()];
							eventDateArray = new String[todayEventsList.size()];
							eventImageLinkArray = new String[todayEventsList.size()];

							for(int i=0;i<todayEventsList.size();i++){
								event = todayEventsList.get(i);
								eventTitleArray[i] = event.getTitle();
								if(event.getDistance()!=0.0)
									eventDateArray[i] = event.getsDate() +" \n " +Double.toString(event.getDistance())+" miles";
								else
									eventDateArray[i] = event.getsDate();					
								eventImageLinkArray[i] = event.getImageLink();
							}
							Log.i(tag , "today event detail"+event.getTitle());
						}else{
							eventTitleArray = new String[1];
							eventDateArray = new String[1];
							eventImageLinkArray = new String[1];
							eventTitleArray[0]= "No Events Scheduled Today Under Category";
							eventDateArray[0] = "Check for Tomorrow/Future";
							eventImageLinkArray[0] = "";
						}

						l1.setAdapter(new EfficientAdapter(ListViewActivity.this,eventTitleArray,eventDateArray,eventImageLinkArray));
						l1.setFocusable(false);
						l1.setOnItemClickListener(new OnItemClickListener() {
							@Override
							public void onItemClick(AdapterView<?> arg0, View arg1,
									int position, long arg3) {
								Intent intent = new Intent(ListViewActivity.this, DisplayActivity.class);
								Bundle b = new Bundle();
								System.out.println("position in list:"+position);
								System.out.println("title name in the list:"+eventTitleArray[position]);
								b.putString("eventTitle", eventTitleArray[position]);
								intent.putExtras(b);
								startActivity(intent);

								Toast.makeText(getApplicationContext(), "Detailed view for the Event", Toast.LENGTH_SHORT).show();


							}
						});

					}
				});

				Button tomorrowButton = (Button) findViewById(R.id.tomorrowButton);
				tomorrowButton.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
						final String [] eventTitleArray;
						String [] eventDateArray;
						String [] eventImageLinkArray;
						
						Event event = new Event();
						System.out.println("Tomorrow button clicked");
						if(tomorrowEventsList.size()!=0){
							eventTitleArray = new String[tomorrowEventsList.size()];
							eventDateArray = new String[tomorrowEventsList.size()];
							eventImageLinkArray = new String[tomorrowEventsList.size()];

							for(int i=0;i<tomorrowEventsList.size();i++){
								event = tomorrowEventsList.get(i);
								eventTitleArray[i] = event.getTitle();
								if(event.getDistance()!=0.0)
									eventDateArray[i] = event.getsDate() +" \n " +Double.toString(event.getDistance())+" miles";
								else
									eventDateArray[i] = event.getsDate();					
								eventImageLinkArray[i] = event.getImageLink();

								Log.i(tag , "tomorrow event detail"+event.getTitle());

							}
						}
						else{
							eventTitleArray = new String[1];
							eventDateArray = new String[1];
							eventImageLinkArray = new String[1];
							eventTitleArray[0]= "No Events Scheduled Tomorrow Under Category";
							eventDateArray[0] = "Check for Today/Future";
							eventImageLinkArray[0] = "";
						}
						l1.setAdapter(new EfficientAdapter(ListViewActivity.this,eventTitleArray,eventDateArray,eventImageLinkArray));
						l1.setFocusable(false);
						l1.setOnItemClickListener(new OnItemClickListener() {
							@Override
							public void onItemClick(AdapterView<?> arg0, View arg1,
									int position, long arg3) {
								Intent intent = new Intent(ListViewActivity.this, DisplayActivity.class);
								Bundle b = new Bundle();
								System.out.println("position in list:"+position);
								System.out.println("title name in the list:"+eventTitleArray[position]);
								b.putString("eventTitle", eventTitleArray[position]);
								intent.putExtras(b);
								startActivity(intent);

								Toast.makeText(getApplicationContext(), "Detailed view for the Event", Toast.LENGTH_SHORT).show();


							}
						});

					}
				});

				Button weekButton = (Button) findViewById(R.id.WeekButton);
				weekButton.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
						final String [] eventTitleArray;
						String [] eventDateArray;
						String [] eventImageLinkArray;

						Event event = new Event();
						System.out.println("week button button clicked");
						if(weekEventsList.size()!=0){
							eventTitleArray = new String[weekEventsList.size()];
							eventDateArray = new String[weekEventsList.size()];
							eventImageLinkArray = new String[weekEventsList.size()];
							for(int i=0;i<weekEventsList.size();i++){
								event = weekEventsList.get(i);
								eventTitleArray[i] = event.getTitle();
								if(event.getDistance()!=0.0)
									eventDateArray[i] = event.getsDate() +" \n " +Double.toString(event.getDistance())+" miles";
								else
									eventDateArray[i] = event.getsDate();					
								eventImageLinkArray[i] = event.getImageLink();

								//Log.i(tag , "weekevent detail"+event.getTitle());

							}
						}
						else{
							eventTitleArray = new String[1];
							eventDateArray = new String[1];
							eventImageLinkArray = new String[1];
							eventTitleArray[0]= "No Events Scheduled In Future Under Category";
							eventDateArray[0] = "Check for Today/Tomorrow";
							eventImageLinkArray[0] = "";
						}
						l1.setAdapter(new EfficientAdapter(ListViewActivity.this,eventTitleArray,eventDateArray,eventImageLinkArray));
						l1.setFocusable(false);
						l1.setOnItemClickListener(new OnItemClickListener() {
							@Override
							public void onItemClick(AdapterView<?> arg0, View arg1,
									int position, long arg3) {
								Intent intent = new Intent(ListViewActivity.this, DisplayActivity.class);
								Bundle b = new Bundle();
								System.out.println("position in list:"+position);
								System.out.println("title name in the list:"+eventTitleArray[position]);
								b.putString("eventTitle", eventTitleArray[position]);
								intent.putExtras(b);
								startActivity(intent);

								Toast.makeText(getApplicationContext(), "Detailed view for the Event", Toast.LENGTH_SHORT).show();


							}
						});


					}
				});

			}
		}






	}

	private class EfficientAdapter extends BaseAdapter{
		private LayoutInflater mInflater;

		private String eventTitleArray[];
		private String eventDateArray[];
		private String eventImageLinkArray[];

		public EfficientAdapter(Context context,String[] eventTitleArray,String[] eventDateArray, String[] eventImageLinkArray){
			mInflater = LayoutInflater.from(context);

			this.eventDateArray=eventDateArray;
			this.eventTitleArray=eventTitleArray;
			this.eventImageLinkArray =eventImageLinkArray;
		}
		public int getCount(){
			//return XmlParser.todayEvents.size()-1;
			return this.eventDateArray.length;
		}
		public Object getItem(int position){
			return position;
		}
		public long getItemId(int position){
			return position;
		}
		public View getView(int position, View convertView, ViewGroup parent){
			ViewHolder holder;
			if(convertView == null){
				convertView = mInflater.inflate(R.layout.listview,null);
				holder = new ViewHolder();
				holder.firstLine = (TextView) convertView.findViewById(R.id.firstLineView);
				holder.secondLine = (TextView) convertView.findViewById(R.id.secondLineView);
				holder.imageView = (ImageView) convertView.findViewById(R.id.linkImage);
				//holder.checkbox = (CheckBox) convertView.findViewById(R.id.star);
				holder.firstLine.setFocusable(false);
				holder.secondLine.setFocusable(false);
				holder.imageView.setFocusable(false);
				//holder.checkbox.setFocusable(false);
				convertView.setTag(holder);
			}else{
				holder = (ViewHolder) convertView.getTag();
			}
			Log.i(tag, "Creating the list");
			holder.firstLine.setText(this.eventTitleArray[position]);
			holder.secondLine.setText(this.eventDateArray[position]);

			Bitmap bitmap;
			try {
				bitmap = BitmapFactory.decodeStream((InputStream)new URL("http://eventur.sis.pitt.edu/images/heinz7.jpg").getContent());
			} catch (MalformedURLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				bitmap = BitmapFactory.decodeFile("assets/heinz7.jpg");//decodeFile(getResources().getAssets().open("icon.png"));
				e1.printStackTrace();
			}
			try {
				try{
					bitmap = BitmapFactory.decodeStream((InputStream)new URL(this.eventImageLinkArray[position]).getContent());}
				catch(Exception e){
					bitmap = BitmapFactory.decodeStream((InputStream)new URL("http://eventur.sis.pitt.edu/images/heinz7.jpg").getContent());
				}

				int width = 0;
				int height =0;
				int newWidth = 50;
				int newHeight = 40;

				try{
					width = bitmap.getWidth();
					height = bitmap.getHeight();
				}
				catch(Exception e){
					width = 30;
					height = 40;
				}
				float scaleWidth = ((float)newWidth)/width;
				float scaleHeight = ((float)newHeight)/height;
				Matrix mat = new Matrix();
				mat.postScale(scaleWidth, scaleHeight);
				try{
					Bitmap newBitmap = Bitmap.createBitmap(bitmap,0,0,width,height,mat,true);
					BitmapDrawable bmd = new BitmapDrawable(newBitmap);
					holder.imageView.setImageDrawable(bmd);
					holder.imageView.setScaleType(ScaleType.CENTER);
				}
				catch(Exception e){

				}


			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}



			return convertView;
		}
		class ViewHolder{
			TextView firstLine;
			TextView secondLine;
			ImageView imageView;
			//CheckBox checkbox;

		}



	}
	
	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub

	}
	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}
	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}
	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}
}
